package com.fp.m7.client.presenter;

import net.customware.gwt.presenter.client.EventBus;
import net.customware.gwt.presenter.client.widget.WidgetDisplay;
import net.customware.gwt.presenter.client.widget.WidgetPresenter;

import com.fp.m7.client.MyMessages;
import com.fp.m7.client.common.IValidatableDisplay;
import com.fp.m7.client.event.InfoEvent;
import com.fp.m7.client.event.InfoEvent.UserMessageType;
import com.fp.m7.shared.ValidationConstants;
import com.fp.m7.shared.ValidationError;
import com.fp.m7.shared.ValidationResult;
import com.google.gwt.core.client.GWT;
import com.google.inject.Inject;

/**
 * Login presenter... handles logging into application? :)
 * 
 * @author 7
 */
public class LoginPresenter extends WidgetPresenter<LoginPresenter.Display> {

    public interface Display extends WidgetDisplay, IValidatableDisplay {

        void setUsername(String username);

        void clear();

    }

    private static MyMessages msg = GWT.create(MyMessages.class);

    private String username;
    private ValidationResult errors = new ValidationResult();

    @Inject
    public LoginPresenter(Display display, EventBus eventBus) {
        super(display, eventBus);
    }

    @Override
    protected void onBind() {
    }

    @Override
    protected void onUnbind() {
    }

    @Override
    protected void onRevealDisplay() {
        display.setUsername(username);
        display.showErrors(errors);
        errors = new ValidationResult();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public boolean getError() {
        return errors != null && !errors.isOk();
    }

    public void setError(boolean isError) {
        if (isError) {
            errors = new ValidationResult(new ValidationError(ValidationConstants.Fields.PASSWORD,
                    ValidationConstants.Messages.INCORRECT));
        } else {
            errors = new ValidationResult();
        }
    }

    public void logoutSuccess() {
        eventBus.fireEvent(new InfoEvent(msg.logoutSuccess(), UserMessageType.SUCCESS));
    }

    public void sessionExpired() {
        eventBus.fireEvent(new InfoEvent(msg.sessionExpired(), UserMessageType.WARNING));
    }

    public void accessDenied() {
        eventBus.fireEvent(new InfoEvent(msg.accessDenied(), UserMessageType.WARNING));
    }
}
